package com.wawei.seeds.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.wawei.seeds.utils.PrefUtils;

/**
 * Created by itachi on 15/8/4.
 */
public class DownloadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            long reference = PrefUtils.getReference(context);

            if (downId != -1 && reference == downId) {
                PrefUtils.markReference(context, -1);

                DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                Intent install = new Intent(Intent.ACTION_VIEW);
                Uri downloadFileUri = manager.getUriForDownloadedFile(downId);
                install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);

                /*
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downId);
                Cursor c = manager.query(query);
                if (c.moveToFirst()) {
                    String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                    if (filename != null) {
                        Log.d("test", filename);
                    }
                }
                */
            }
        }
    }
}
